package com.zhijian.wharf.aop;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author HCG
 * @version 1.0
 * @date 2024-06-17
 */
public class HttpContextUtils {

    /**
     * 获取当前请求
     *
     * @return 请求
     */
    public static HttpServletRequest getHttpServletRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }

    /**
     * 获取真正的ip
     *
     * @param request 请求
     * @return
     */
    public static String getRealIp(HttpServletRequest request) {
        //
        String ip = request.getHeader("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 处理多IP的情况（只取第一个IP）
        if (ip != null && ip.contains(",")) {
            String[] ipArray = ip.split(",");
            ip = ipArray[0];
        }
        return ip;
    }

    /**
     * 获取所有头
     *
     * @param request 请求
     * @return 所有请求头
     */
    public static String getAllHeader(HttpServletRequest request) {
        Enumeration<String> eHeaders = request.getHeaderNames();
        Map<String, String> map = new HashMap<>();
        while (eHeaders.hasMoreElements()) {
            String name = eHeaders.nextElement();
            String val = request.getHeader(name);
            map.put(name, val);
        }
        return JSONObject.toJSONString(map);
    }

}
